// 导入安装好的 uni-app-fetch 模块
import { createUniFetch } from 'uni-app-fetch'
import { getCurrentPageRoute, getTabBarPagePathList, toast } from '../utils/utils'
import { useUserStore } from '@/stores/user.js'

// 配置符合自身业务的请求对象
export const uniFetch = createUniFetch({
  loading: { title: '正在加载...' },
  baseURL: 'https://slwl-api.itheima.net',
  intercept: {
    // 请求拦截器
    request(config) {
      const { token } = useUserStore()
      if (token) {
        config.header = Object.assign({}, { Authorization: token }, config.header)
      }
      return config
    },
    // 响应拦截器
    response(res) {
      const { data, statusCode } = res
      if (statusCode === 401) {
        //回跳地址
        const returnURL = getCurrentPageRoute()
        //tabBar地址列表
        const tabBarPagePathList = getTabBarPagePathList()
        //回跳方式
        const returnType = tabBarPagePathList.includes(returnURL.slice(1)) ? 'switchTab' : 'redirectTo'
        uni.redirectTo({
          url: `/pages/login/index?returnType=${returnType}&returnURL=${returnURL}`,
        })
        return new Promise(() => {})
      }
      if (data.code !== 200) {
        toast(data.msg)
        return Promise.reject(res)
      }
      return data
    },
  },
})
